
export class BookmarkUtils {
    /**
     * 获取当前书签数据并格式化成 JSON 字符串返回
     * @returns {string} 格式化的书签数据 JSON 字符串
     */
    exportBookmarksToJson() {
        return new Promise((resolve, reject) => {
            chrome.bookmarks.getSubTree('1', (bookmarkTreeNodes) => {
                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError);
                } else {
                    resolve(JSON.stringify(bookmarkTreeNodes, null, 2));
                }
            });
        });
    }

    // 清除现有书签
    removeAll() {
        chrome.bookmarks.getSubTree('1', (currentTree) => {
            if (currentTree && currentTree[0] && currentTree[0].children) {
                currentTree[0].children.forEach((folder) => {
                    if (folder.id ) {
                        console.log('删除书签：', folder.id);
                        chrome.bookmarks.removeTree(folder.id, () => {
                            // 记录内部操作标志
                            const key1 = `removed_${folder.id}`;
                            let data = { };
                            data[key1] = true;
                            chrome.storage.local.set(data);
                         });
                    }
                });
            }
        });
    }

     /**
     * 检查书签ID是否存在
     * @param {string} bookmarkId - 要检查的书签ID（必须是字符串类型）
     * @return {Promise<boolean>} - 返回ID是否存在的Promise
     */
    checkBookmarkExists(bookmarkId) {
        return new Promise((resolve) => {
            // 使用chrome.bookmarks.get直接查询ID
            chrome.bookmarks.get(bookmarkId, (results) => {
                // 处理可能的API错误
                if (chrome.runtime.lastError) {
                    // {message: "Can't find bookmark for id."}
                    if(chrome.runtime.lastError.message != null &&  chrome.runtime.lastError.message.indexOf("Can't find bookmark for id") != -1) {
                        resolve(false);
                        return;    
                    }
                    console.error('书签查询错误:', chrome.runtime.lastError);
                    resolve(false);
                    return;
                }
                // 如果结果数组长度大于0，则ID存在
                resolve(results.length > 0);
            });
        });
    }

    /**
     * 将 JSON 格式的书签数据导入到当前浏览器
     * @param {string} jsonString - 要导入的 JSON 格式的书签数据
     */
    importBookmarksFromJson(jsonString) {
        try {
            const bookmarkData = JSON.parse(jsonString);
            
            // 导入新书签
            function traverseAndCreate(nodes, parentId = '1') {
                nodes.forEach((node) => {
                    if (node.id === '1') {
                        traverseAndCreate(node.children, node.id);
                        return; // 跳过ID为'1'的默认书签栏节点
                    }
                    const createProps = {
                        title: node.title,
                        parentId: parentId
                    };

                    if (node.url) {
                        createProps.url = node.url;
                    }
                    if (node.index !== undefined && node.index !== null) {
                        createProps.index = node.index;
                    }

                    chrome.bookmarks.create(createProps, (newNode) => {
                        // 记录内部操作标志
                        const key1 = `created_${newNode.id}`; 
                        let data = {};
                        data[key1] = true;
                        chrome.storage.local.set(data);
                        if (node.children && node.children.length > 0) {
                            traverseAndCreate(node.children, newNode.id);
                        }
                    });
                });
            }
  
            traverseAndCreate(bookmarkData); 
            return true;
        } catch (error) {
            console.error('导入新书签失败:', error);
            return  false;
        }

    }

}